import 'package:flutter/material.dart';

class CenterFocusSlider extends StatefulWidget {
  final List<Widget> items;
  final double itemWidth;
  final double itemHeight;
  final double centerScale; // 中间项放大比例
  final double edgeOpacity; // 边缘项透明度

  const CenterFocusSlider({
    super.key,
    required this.items,
    this.itemWidth = 200,
    this.itemHeight = 300,
    this.centerScale = 1.2,
    this.edgeOpacity = 0.6,
  });

  @override
  State<CenterFocusSlider> createState() => _CenterFocusSliderState();
}

class _CenterFocusSliderState extends State<CenterFocusSlider> {
  late PageController _pageController;
  double _currentPage = 0;

  @override
  void initState() {
    super.initState();
    // 初始化 PageController，设置初始页面和视图比例
    _pageController = PageController(
      initialPage: 0,
      viewportFraction: widget.itemWidth / MediaQuery.of(context).size.width,
    )..addListener(() {
        // 监听页面滚动，更新当前页码
        setState(() {
          _currentPage = _pageController.page!;
        });
      });
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  // 计算每个 item 的样式（缩放、透明度）
  Matrix4 _buildTransform(int index) {
    final double pageDiff = (_currentPage - index).abs();

    // 中间项放大，边缘项缩小
    final double scale = 1 - (pageDiff * (1 - widget.centerScale));

    // 应用缩放变换
    return Matrix4.identity()..scale(scale);
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: widget.itemHeight * widget.centerScale,
      child: PageView.builder(
        controller: _pageController,
        itemCount: widget.items.length,
        // 禁用无限滚动（如需可改为 true）
        allowImplicitScrolling: false,
        itemBuilder: (context, index) {
          return AnimatedBuilder(
            animation: _pageController,
            builder: (context, child) {
              // 计算当前 item 与中间位置的距离
              final double pageDiff = (_currentPage - index).abs();

              // 距离中间越远，透明度越低
              final double opacity = 1 - (pageDiff * (1 - widget.edgeOpacity));

              return Opacity(
                opacity: opacity,
                child: Transform(
                  transform: _buildTransform(index),
                  alignment: Alignment.center,
                  child: child,
                ),
              );
            },
            child: Padding(
              // 左右间距，确保中间项居中
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: widget.items[index],
            ),
          );
        },
      ),
    );
  }
}
